package com.web_bloks.api.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;
import com.web_bloks.system.client.Logger;

/**
 * 
 * @author Jean-Lou Dupont
 *
 */
public class User {

	String username   = null;
	String groups     = null;
	String login_url  = null;
	String logout_url = null;
	
	protected User() {	
	}
	
	public static User fromJSON(JSONValue value) {
		
		if (null == value)
			return null;
		
		//Logger.logInfo("User.fromJSON: value.toString()=" + value.toString() );
		
		User user = GWT.create(User.class);
		
		JSONObject obj = null;
		
		try {
			obj = value.isObject();
			user.username   = obj.get("username").isString().stringValue();
			user.groups     = obj.get("groups").isString().stringValue();
			user.login_url  = obj.get("login_url").isString().stringValue();
			user.logout_url = obj.get("logout_url").isString().stringValue();
		} catch(Exception e) {
			// any error...
			Logger.logWarn("User.fromJSON: error extracting parameters, msg="+e.getMessage());
		}
		
		return user;
	}
	
	public String getLoginUrl() {
		return login_url;
	}
	public String getLogoutUrl() {
		return logout_url;
	}
	
	/**
	 * Verifies if the user is part of group
	 * 
	 * @param group String
	 * @return result Boolean
	 */
	public boolean isMemberOf(String group) {
		if (null == groups || groups.length()==0)
			return false;
		
		return groups.indexOf(group) != -1;
	}
	
	/**
	 * 
	 * @return
	 */
	public boolean isLogged() {
		return (username != null && username.length()>0);
	}
	
}//END.

/* Template used:
 
	{
	"name"  : "{{ username }}",
	"groups": "{{ group_admin }}",
	"login" : "{{ login_url }}",
	"logout": "{{ logout_url }}",	
	}
	
*/